var cell;
var command;
var subselect = "";
var selectid = null;
var tab;
var period = new Date();
var del = "";
var cash = null;
var card = null;

$(window).resize(contentSize).ready(defaultInit);

function defaultInit() {
	$(".header-menu").click(function() {
		$(".header-menu").removeClass("header-menu-select");
		$(this).addClass("header-menu-select");
	});
	$("#tabs").tabs({
		spinner: '불러오는 중',
		fx: { opacity: 'toggle' },
		show: tabShown,
		select: tabSelect,
		ajaxOptions: { async: false }
	});

	$("#del_dialog").dialog({
		bgiframe: true,
		resizable: false,
		autoOpen: false,
		height:50,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			'삭제하기': function() {
				delRow();
				$(this).dialog('close');
			},
			'취소': function() {
				$(this).dialog('close');
			}
		}
	});
	$.datepicker.setDefaults({dateFormat: 'yy.mm.dd'});
	$('#datepicker').datepicker();
	$("#calculator").calculator({
		showAnim: 'blind',
		duration: 'normal',
		layout: ['_7_8_9_+' + $.calculator.CLOSE,
		         '_4_5_6_-' + $.calculator.USE,
		         '_1_2_3_*' + $.calculator.ERASE,
		         '_0_._=_/']
	});
	$(".contents_period_move").click(periodMove);
}

function cellEditorInit() {
	$("#date_command").datepicker({
		onSelect: function(dateText, inst) { command.attr("value",dateText); command.change(); }
	}).change(hideInput).keypress(keySensor);
	$("#suggest_command").blur(hideInput).keypress(keySensor);
	$("#number_command").keyup(numberFormat).blur(hideInput).keypress(keySensor);
	$("#cardtype_command").focus(popSelect).blur(hideInput).keypress(keySensor);
	$("#cate_command").focus(popSelect).blur(hideInput).keypress(keySensor);
	$(".cate_select li").mouseover(popSelectSub);

	setSelectable();

	initPeriod();
	contentsInitOnce();
}

function contentsInitOnce() {
	$("#all-check").live('click',allCheck);
	$(".yyyymmdd").live('click',popInput);
	$(".description").live('click',popInput);
	$(".cash").live('click',popInput);
	$(".cate").live('click',popInput);
}

function contentsInit() {
	contentSize();
	initDelBtn();
	initSaveBtn();
	if (tab == 0) {
		$(".card").live('click',popInput);
		$(".cardtype").live('click',popInput);
		$(".disabled").removeClass("disabled");
	} else {
		$(".card").die('click',popInput);
		$(".cardtype").die('click',popInput);
	}
	$(".numbertd").each(numberToMoneyInit);
	$(".numberTotal").each(numberToMoneyInit);
	monthStat();
}

function allCheck(){
	var checked = $(this).attr("checked");
	$("#grid_table input:checkbox").each(function() {
		$(this).attr("checked",checked);
	});
	$("._0 input:checkbox").removeAttr("checked");
}

function initSaveBtn() {
	$('#saveBtn').click(function() {
		// 뭘하지??
	})
	.hover(
		function(){
			$(this).addClass("ui-state-hover");
		},
		function(){
			$(this).removeClass("ui-state-hover");
		}
	).mousedown(function(){
		$(this).addClass("ui-state-active");
	})
	.mouseup(function(){
			$(this).removeClass("ui-state-active");
	});
}

function initDelBtn() {
	$('#delBtn').click(function() {
		delChecked();
		if (del != "" && del != null)
			$('#del_dialog').dialog('open');
	})
	.hover(
		function(){
			$(this).addClass("ui-state-hover");
		},
		function(){
			$(this).removeClass("ui-state-hover");
		}
	).mousedown(function(){
		$(this).addClass("ui-state-active");
	})
	.mouseup(function(){
			$(this).removeClass("ui-state-active");
	});
}
function delChecked() {
	del = "";
	$("#grid_table input:checked").each(function() {
		del = del + $(this).attr("class");
	});
}
function delRow() {
	cash = 0;
	card = 0;
	$.post("/moneybook/c", {
		'cmd': 'delete',
		'seq': del
	}, function(data) {
		$("#grid_table input:checked").each(function() {
			var tr = $(this).parent().parent();
			cash += Number(moneyToNumber(tr.children(".cash").text()));
			card += Number(moneyToNumber(tr.children(".card").text()));
			tr.remove();
		});
		totalValueUpdate(0,0);
		contentSize();
	});
}

function keySensor(e) {
	if (e.keyCode == 9 || e.keyCode == 13) {	// TAB || ENTER
		e.returnValue = false; // IE
		e.preventDefault();	// FF
		command.blur();
		cell.next().click();
	}
}

function monthStat() {
	if (tab==0) {
		$("#month_out").text($("#bothTotal").text());
		$("#month_in").text($("#leftTotal").text());
	} else if (tab==1) {
		$("#month_out").text($("#leftTotal").text());
		$("#month_in").text($("#bothTotal").text());
	} else {
		$("#month_in").text($("#leftTotal").text());
		$("#month_out").text($("#centerTotal").text());
	}
	var sum = moneyToNumber($("#month_in").text()) - moneyToNumber($("#month_out").text());
	if (sum < 0) {
		$("#month_sum").addClass("month_sum-red");
	} else {
		$("#month_sum").removeClass("month_sum-red");
	}
	$("#month_sum").text(numberToMoney(String(sum)));
}

function sendRow() {
	var trClass = cell.parent().attr("class");
	var tdArray = $('.'+trClass+" td");
	var nowCash = moneyToNumber(tdArray[3].innerHTML);
	var nowCard = moneyToNumber(tdArray[4].innerHTML);
	$.post("/moneybook/c", {
		'tab': tab,
		'cmd': 'save',
		'seq': trClass.substring(1),
		'date': getTime(tdArray[1].innerHTML),
		'description': tdArray[2].innerHTML,
		'cash': nowCash,
		'card': nowCard,
		'cardtype': getCardType(tdArray[5]),
		'category': getCategory(tdArray[6])
	}, function(data) {
		if (data != null && data != "") {
			setSequence(data);
			addRow();
		}
		totalValueUpdate(Number(nowCash),Number(nowCard));
	});
}

function totalValueUpdate(nowCash,nowCard) {
	nowCash -= cash;
	cash = null;
	nowCard -= card;
	card = null;
	nowCash += Number(moneyToNumber($("#cashTotal").text()));
	nowCard += Number(moneyToNumber($("#cardTotal").text()));
	$("#cashTotal").text(numberToMoney(String(nowCash)));
	$("#cardTotal").text(numberToMoney(String(nowCard)));
	var total = Number(moneyToNumber($("#cardTotal").text())) + Number(moneyToNumber($("#cashTotal").text()));
	$("#bothTotal").text(numberToMoney(String(total)));
	monthStat();
}

function setSequence(seq) {
	seq = "_"+seq.replace(/\D/g,"");
	$("._0 .seq input:checkbox").removeAttr("disabled").addClass(seq);
	$("._0").attr("class",seq);
}

function getCategory(td) {
	var text = jQuery(td).children().attr("class");
	return text.replace("cate_","");
}

function getCardType(td) {
	var text = jQuery(td).children().attr("class");
	return text.replace("cardtype_","");
}

function getTime(str) {
	str = str.split(".");
	var date = new Date();
	date.setFullYear(str[0], str[1]-1, str[2]);
	return date.getTime();
}

function initPeriod() {
	var month = period.getMonth();
	var year = period.getFullYear();
	var days = getLastDay(year,month);

	month += 1;
	if (month < 10)
		month = '0'+month;

	$("#contents_period_first").text(year+'.'+month+'.01');
	$("#contents_period_last").text(year+'.'+month+'.'+days);
}

function periodMove() {
	var year = period.getFullYear();
	var month = period.getMonth();

	if ($(this).attr("id") == "contents_period_left") {
		if (--month < 0) {
			year--;
			month = 11;
		}
	} else {
		if (++month > 11) {
			year++;
			month = 0;
		}
	}
	period.setFullYear(year, month, 1);
	for (var i=0; i<3; i++) {
		$("#tabs").tabs('url', i, "c?cmd=tabs&tab="+i+"&date="+period.getTime());
	}
	initPeriod();
	$("#tabs").tabs('load', tab);
}

function getLastDay(year, month) {
	var dayOfMonth = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
	if ( ((year %4 == 0) && (year % 100 != 0))||(year % 400 == 0) )
		dayOfMonth[1] = 29;
	var days = dayOfMonth[month];
	return days;
}

function tabShown() {
	$(".ui-state-focus").removeClass("ui-state-focus");
	$(".grid_panel").scrollTop($(this).height());
	$("._0 .description").click();
	$(".grid_panel").scroll(scrollCommand);
}
function tabSelect() {
	$(".ui-tabs-panel").empty();
}
function scrollCommand() {
	$(".command:visible").blur();
}

function getToday() {
	var d = new Date();
	var month = d.getMonth()+1;
	month = month.toString();
	if (month.length < 2) {
		month = '0'+month;
	}
	var date = d.getDate().toString();
	if (date.length < 2) {
		date = '0'+date;
	}
	return d.getFullYear()+'.'+month+'.'+date;
}

// 중앙 레이어 사이즈 조절.
function contentSize() {
	$(".command:visible").blur();
	var height = $(window).height() - $("#footer").outerHeight()
				- $("#top").outerHeight() - $("#header").outerHeight();
	if (height < 500)
		height = 500;
	$(".middle").height(height);
	height = height -172;
	$(".grid_panel").height(height);
	var table = (countRows() * 26);
	if (height > table)
		height = height - table;
	else height = 260;
	$("#grid_over td").height(height);
}

function countRows() {
	return document.getElementById("grid_table").rows.length;
}

function addRow() {
	var tb = document.getElementById("grid_table");
	var defaultRow = tb.rows[0];
	var row = tb.insertRow(tb.rows.length);
	row.className = "_0";
	var cell;
	for(var i=0; i<defaultRow.cells.length; i++) {
		cell = row.insertCell(i);
		cell.className = defaultRow.cells[i].className;
	}
	row.cells[0].innerHTML = '<input type="checkbox" disabled="disabled"/>';
	row.cells[1].innerHTML = getToday();
	row.cells[3].innerHTML = 0;
	row.cells[4].innerHTML = 0;
	row.cells[5].innerHTML = '<div class="cardtype_0"></div>';
	row.cells[6].innerHTML = '<span class="cate_0">미분류</span>';

	if (tab != 0) {
		jQuery(row.cells[4]).addClass("disabled");
		jQuery(row.cells[5]).addClass("disabled");
	}
}

function setSelectable() {
	$(".selectable").selectable({
		tolerance: 'fit',
		selected: function(){
			$(".ui-selected").each(function(){
				selectid = $(this).attr("id");
				var value = selectid.replace("cate_","").replace("cardtype_","");
				var txt = $(this).text();
				if (value == 0) {
					txt = "";
				} else if (value < 1000) {
					// nothing
				} else if (value % 10 == 0) {
					var se = $("#"+selectid+"_sub li:last");
					selectid = se.attr("id");
					txt = txt+"> "+se.text();
				} else {
					txt = subselect+"> "+txt;
				}
				command.attr("value",txt);
				subselect = "";

				$(this).removeClass("tr_hover");
				$(this).removeClass("ui-selected");
				command.blur();
			});
		}
	});
}

function numberFormat(e) {
	var str = $(this).attr("value");
	str = str.replace(/\D/g, "");
	$(this).attr("value", str);
}

function popInput() {
	cell = $(this);

	var pos = cell.position();

	if (cell.hasClass("yyyymmdd")) {
		command = $("#date_command");
	} else if (cell.hasClass("description")) {
		command = $("#suggest_command");
	} else if (cell.hasClass("cash") || cell.hasClass("card")) {
		command = $("#number_command");
	} else if (cell.hasClass("cardtype")) {
		command = $("#cardtype_command");
	} else if (cell.hasClass("cate")) {
		command = $("#cate_command");
	}
	command.attr("value",cell.text().trim());
	command.css({
		'left':pos.left,
		'top':pos.top,
		'height':'17px',
		'width':cell.width(),
		'display':'block'
	});
	command.focus();
	command.select();
}


function popSelectSub() {
	$(".subselect").hide();
	subselect = $(this).text();
	var pos = command.position();
	var pos1 = $(this).position();
	var id = "#" + $(this).attr("id") + "_sub";
	var pop = $(id);
	pop.css({
		'left':pos.left+70,
		'top':pos1.top+pos.top+30,
		'width':83,
		'display':'block'
	});
}

function popSelect() {
	var pos = command.position();
	var pop;
	if (cell.hasClass("cardtype")) {
		pop = $("#cardtype_select");
	} else if (cell.hasClass("cate")) {
		pop = $("#cate_select_"+tab);
	}
	pop.css({
		'left':pos.left,
		'top':pos.top+command.outerHeight(),
		'width':command.width(),
		'display':'block'
	});
}

function hideInput() {
	if (cell.hasClass("numbertd")) {
		if (cell.hasClass("cash")) {
			cash = Number(moneyToNumber(cell.text()));
			card = Number(moneyToNumber(cell.next().text()));
		} else {
			card = Number(moneyToNumber(cell.text()));
			cash = Number(moneyToNumber(cell.prev().text()));
		}
		command.attr("value", numberToMoney(command.attr("value")));
	}
	if (cell.text() != command.attr("value")) {
		if (selectid != null) {
			cell.children().attr("class",selectid).text(command.attr("value"));
			selectid = null;
		} else {
			cell.text(command.attr("value"));
		}
		sendRow();
	}
	$(this).removeAttr("value");
	$(".command:visible").hide();
}

function numberToMoneyInit() {
	$(this).text(numberToMoney($(this).text()));
}

function numberToMoney(str) {
	var arr = str.replace(/\D/g, "").split("");
	var result = "";
	var i = 3;
	while (arr.length > 0) {
		if (result.length == i) {
			result = "," + result;
			i = i+4;
		}
		result = Number(arr.pop()) + result;
	}
	if (result == "")
		result = "0";
	return result;
}

function moneyToNumber(text) {
	return text.replace(/,/g,"");
}


